#include "SDL_mixer.h"

#include "MusicManager.hpp"
#include "Audio.hpp"

namespace fge
{

static MusicManager *callbackTarget;
static void MusicFinishedCallback()
{
	callbackTarget->MusicFinishedCallback();
}

MusicManager::MusicManager()
	: currentSong(NULL)
{
	callbackTarget = this;
	Mix_HookMusicFinished(&fge::MusicFinishedCallback);
}

MusicManager::~MusicManager()
{
}

void MusicManager::Play(Song *song, float fadeOut, float fadeIn)
{
	bool currentlyPlaying = Mix_GetMusicType(NULL) != MUS_NONE;

	songs.clear();

	if(currentlyPlaying && fadeOut > 0)
	{
		currentSong = NULL;
		songs.push_back(song);
		this->fadeIn = fadeIn;

		Mix_FadeOutMusic(static_cast<int>(fadeOut * 1000));
	}
	else
	{
		currentSong = song;
		this->fadeIn = 0;

		Mix_FadeInMusic(song->GetSongData(), 0, static_cast<int>(fadeIn * 1000));
	}
}

void MusicManager::Queue(Song *song)
{
	songs.push_back(song);
}

void MusicManager::Stop(float fadeOut)
{
	songs.clear();
	currentSong = NULL;

	Mix_FadeOutMusic(static_cast<int>(fadeOut * 1000));
}

void MusicManager::MusicFinishedCallback()
{
	if(currentSong != NULL)
		songs.push_back(currentSong);

	if(songs.size() == 0)
		return;

	currentSong = songs.front();
	songs.pop_front();
	Mix_FadeInMusic(currentSong->GetSongData(), 0, static_cast<int>(fadeIn * 1000));
	fadeIn = 0;
}

}
